// 这里baseurl获取的是config.json中配置的 http://192.168.3.248:8096 ，是写死的
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
// import value from "../static/config.json";


declare module 'axios' {
    export interface AxiosResponse<T> {
        code: number;
        message: string;
        success: boolean;
        timestamp: number;
        [key: string]: T;
        [key: number]: T;
    }
}

//请求默认配置文件
var value: any;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            value = JSON.parse(xhr.responseText);
            sessionStorage.setItem("httpUploadUrl", value.video.serviceUrl)
        }
    }
};

// 获取默认资源
xhr.open("get", './config.json', false);
xhr.send(null);


interface McAxiosRequestConfig extends AxiosRequestConfig {
    extraConfig?: {
        tokenRetryCount: number; // 标记当前请求的csrf token重试次数
    };
}
const timeout = 60000; // 请求超时时间和延迟请求超时时间统一设置
const config: McAxiosRequestConfig = {
    baseURL: value.video.serviceUrl,
    timeout,
    headers: {
    }
};

const defHttp = axios.create(config);

defHttp.interceptors.request.use(async (config: McAxiosRequestConfig) => {
    if (!config.extraConfig?.tokenRetryCount) {
        config.extraConfig = {
            tokenRetryCount: 0,
        };
    }
    (config.headers as any)["X-Access-Token"] = sessionStorage.getItem("token");
    return config;
});

defHttp.interceptors.response.use(
    (response) => {
        if (response.data.code == 200) {
            ElMessage.success(response.data.message);
        }
        return response.data;
    },
    async (err) => {
        if (axios.isCancel(err)) {
            // 取消的请求，不报错
            return;
        }

        if (err.message === "Network Error") {
            console.log("Network Error");

            return;
        }
        if (err.message.includes("timeout")) {
            return;
        }
        if (err.response?.status >= 500) {
            return;
        }

        const { data: responseData } = err.response || {};
        const { code } = responseData || {};
        if (code) {
            switch (parseInt(code)) {
                case 4001:
                    break;
                case 401:
                    sessionStorage.clear();
                    location.reload();
                    break;
                default:
                    break;
            }
        }
        return err.response;
    }
);

const get = (url: string, params?: any): Promise<AxiosResponse<any>> => {
    return defHttp.get(url, { params });
}
const getHeader = (url: string, data?: any, headers?: any): Promise<AxiosResponse<any>> => {
    // console.log(data)
    return defHttp.get(url, data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
}
const post = (url: string, data?: any): Promise<AxiosResponse<any>> => {
    return defHttp.post(url, data);
}
export { get, post, defHttp, getHeader };